package cn.msqweb.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.msqweb.constant.ManagerConstants;
import cn.msqweb.entity.SysMenu;
import cn.msqweb.ex.handler.ex.BusinessException;
import cn.msqweb.mapper.SysMenuMapper;
import cn.msqweb.service.SysMenuService;
import cn.msqweb.util.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 20120
* @description 针对表【sys_menu(菜单管理)】的数据库操作Service实现
* @createDate 2024-06-19 18:15:11
*/
@Service(value = "sysMenuService")
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService {
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Set<SysMenu> selectSysMenuListByUserID(Long loginSysUserID) {
        //redis 中查询
        String SysUserMenusJsonStr = stringRedisTemplate.opsForValue().get(ManagerConstants.SYS_MENU_PREFIX + loginSysUserID);
        Set<SysMenu> sysMenus = new HashSet<>();
        if (StringUtils.hasText(SysUserMenusJsonStr)){
            sysMenus = new HashSet<>(JSONObject.parseArray(SysUserMenusJsonStr, SysMenu.class));

        }else {
            //查询用户权限
            sysMenus = sysMenuMapper.selectSysMenuListByUserID(loginSysUserID);
            System.out.println("sysMenus = " + sysMenus);
            //存放redis中 有效时长为24小时
            stringRedisTemplate.opsForValue().set(ManagerConstants.SYS_MENU_PREFIX + loginSysUserID, JsonUtils.objToJson(sysMenus), Duration.ofHours(24));
        }


        return transformTree(sysMenus,0L);
    }

    @Override
    public Boolean removeSysMenu(Long menuId) {
        // 根据标识查询节点的子节点集合
        List<SysMenu> childList = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getParentId, menuId)
        );
        // 判断是否有值
        if (CollectionUtil.isNotEmpty(childList) && childList.size() != 0) {
            // 说明：当前节点包含子节点集合，即不可删除
            throw new BusinessException("当前节点包含子节点集合，即不可删除");
        }
        return sysMenuMapper.deleteById(menuId)>0;
    }

    /**
     * 集合转树结构
     * @param sysMenus
     * @param pid
     * @return
     */
    private Set<SysMenu> transformTree(Set<SysMenu> sysMenus, Long pid) {
        //二级菜单深度查询
//        Set<SysMenu> roots = sysMenus.stream().filter(sysMenu -> sysMenu.getParent_id().equals(pid)).collect(Collectors.toSet());
//        roots.forEach(r ->{
//            Set<SysMenu> childNode = sysMenus.stream()
//                    .filter(sysMenu -> sysMenu.getParent_id().equals(r.getMenu_id()))
//                    .collect(Collectors.toSet());
//            r.setChildNode(childNode);
//        });

        //菜单深度未知
        Set<SysMenu> roots = sysMenus.stream().filter(sysMenu -> sysMenu.getParentId().equals(pid)).collect(Collectors.toSet());
        roots.forEach(r->r.setList(transformTree(sysMenus,r.getMenuId())));

        return roots;
    }


}




